package cn.zzuisa.news.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.zzuisa.news.entity.User;
import cn.zzuisa.news.enums.CommonEnums;
import cn.zzuisa.news.service.UserService;
import cn.zzuisa.news.service.impl.UserServiceImpl;
import cn.zzuisa.news.util.JsonUtil;
import cn.zzuisa.news.util.ResultVOUtil;

@WebServlet(name = "login", urlPatterns = "/login", asyncSupported = true)
public class LoginServlet extends HttpServlet {
	private UserService userServiceImpl = new UserServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String method = req.getParameter("method");
		if (method == null)
			req.getRequestDispatcher("WEB-INF/ftl/user/login.ftl").forward(req, resp);
		if (method.equals("login")) {
			/** 获取ajax信息 json			 */
			String c = JsonUtil.getStrResponse(req);
			/** 转为对应的Form实体类*/
			JsonObject user = new JsonParser().parse(c).getAsJsonObject();
			
			User auth = userServiceImpl.login(user.get("username").getAsString(), user.get("password").getAsString());
			if (auth != null) {
				if (auth.getState() == 1)
					resp.getWriter().println(JsonUtil.setData(ResultVOUtil.failed(CommonEnums.USER_LOCKED)));
				else {
					HttpSession session = req.getSession();
					session.setMaxInactiveInterval(6 * 60 * 60);
					session.setAttribute("user", auth);
					resp.getWriter().println(JsonUtil.setData(ResultVOUtil.success(auth)));
					// req.getRequestDispatcher("WEB-INF/ftl/index/index.ftl").forward(req, resp);
				}
			} else {
				resp.getWriter().println(JsonUtil.setData(ResultVOUtil.failed(CommonEnums.LOGIN_FAIL)));
			}
		}
		if (method.equals("logout")) {
			HttpSession session = req.getSession();
			session.removeAttribute("user");
			resp.sendRedirect("index");

		}
	}
}
